/*
 * kbdctl.c
 *
 *  Created on: Mar 12, 2013
 *      Author: ismith
 */

#include "kbdctl.h"
#include "random.h"
#include <stdlib.h>
#include <ncurses/curses.h>


KbdctlPtr kbdctl_new(void)
{
	KbdctlPtr kbd = (KbdctlPtr)malloc(sizeof(KbdctlStr));
	kbd->read_position = 0;
	kbd->write_position = 0;

	return kbd;
}

void kbdctl_initialize(KbdctlPtr kbd)
{
	kbd->read_position = 0;
	kbd->write_position = 0;
	kbd->buffer_full = 0;
	int i;
	for (i = 0; i < BUFFER_LENGTH; i++)
	{
		kbd->buffer[i] = random_byte();
	}

}

void kbdctl_free(KbdctlPtr kbd)
{
	free(kbd);
}

void kbdctl_writechar(KbdctlPtr kbd, Byte character)
{
	if (kbd->buffer_full == TRUE)
	{
		beep();
		return;
	}

	kbd->buffer[kbd->write_position] = character;
	kbd->write_position++;

	if (kbd->write_position == BUFFER_LENGTH)
		kbd->write_position = 0;

	if (kbd->write_position == kbd->read_position)
	{
		kbd->buffer_full = TRUE;
	}

}

Bit kbdctl_haschar(KbdctlPtr kbd)
{
	if ((kbd->buffer_full == TRUE) || (kbd->read_position != kbd->write_position))
		return TRUE;
	else
		return FALSE;
}

Byte kbdctl_readchar(KbdctlPtr kbd)
{
	if (kbdctl_haschar(kbd) == FALSE)
	{
		return 0x00;
	}

	Byte character = kbd->buffer[kbd->read_position];
	kbd->read_position++;

	if (kbd->read_position == BUFFER_LENGTH)
		kbd->read_position = 0;

	kbd->buffer_full = FALSE;

	return character;
}
